package nowcoder.offer;

import java.util.Stack;

/**
 * 二叉搜索树的第K个结点
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-08-30 12:30
 */
public class KthNode {


    TreeNode solution(TreeNode pRoot,int k){
        if (pRoot==null || k == 0) return null;
        /**
         * 二叉搜索树的中序遍历
         * 非递归实现
          */
        Stack<TreeNode> stack = new Stack<>();

        int count = 0;
        TreeNode node = pRoot;
        while (node != null || !stack.isEmpty()){
            if (node != null){
                stack.push(node);
                node  = node.left;
            }else {
                node = stack.pop();
                count++;
                if (count == k) return node;
                node = node.right;
            }
        }

        return null;
    }


}
